import { useParams } from '@@/exports';
import { PageContainer } from '@ant-design/pro-components';
import { marked } from 'marked'
import 'highlight.js/styles/base16/darcula.css'

import {
    Card,
    Image, List, Avatar, notification
} from 'antd';
import React, { useEffect, useState,useRef } from 'react';
import {
    EditFilled,
    EllipsisOutlined, LikeOutlined, MessageOutlined, StarOutlined,SmileTwoTone,
    VideoCameraFilled
} from "@ant-design/icons";
import CommentModal from '@/pages/forum/components/CommentModal';
import {keyframes} from "antd-style";
import { history, useIntl } from '@umijs/max';
import {
    getArticleDetailUsingGet,
    hotArticleListUsingGet,
    likeArticleUsingPost
} from "@/services/openAPI-backend/articleController";
import {listCommentByPageUsingGet} from "@/services/openAPI-backend/articleCommentController";
/**
 * 每个用户都能看到的接口表格
 * @param param0
 * @returns
 */

const Index: React.FC = () => {
    const param = useParams();

    let content = "";
    const [loading, setLoading] = useState(false);
    const [commentModalOpen, handleCommentModalOpen] = useState<boolean>(false);
    const [commentList, setCommentList] = useState<API.Comment[]>();
    const [hotArticleList, setHotArticleList] = useState<API.ArticleVo[]>([]);
    const ondrawClose = () => {
        handleCommentModalOpen(false);
    };
    const getComment = async (id) => {
        try{
            const res = await listCommentByPageUsingGet({
                articleId:id,
                pageNum: 1,
                pageSize: 10,
            });
            setCommentList(res.data?.rows);
            console.log(commentList);
        }catch (e){
            console.log(e);
        }
    }
    marked.use({
        // 开启异步渲染
        pedantic: false,
        gfm: true,
        mangle: false,
        headerIds: false
    })
    const [data,loadData] = useState<API.ArticleDetailVo>();
    const LoadDta = async () => {
        const numberElement = document.getElementById("content");
        const res = await getArticleDetailUsingGet({
            id: param.id == null? 0 : Number(param.id),
        })
            if (res && res.data && res.data.content) {
                loadData(res.data)
            } else {
                console.error('Content is missing or data is incorrectly formatted.');
            }


    };
    const onGood = async () => {
        const res = await likeArticleUsingPost({
            articleId: param.id == null? 0 : Number(param.id),
        })
        if (res?.data) {
            notification.success({
                message: res.data,
                description: res.data=='点赞已取消'?'希望下一篇文章可以打动你':'感谢您对作者的喜爱',
            });
            LoadDta();
        }
    }

    const loadHotArticleList = async () => {
        setLoading(true)
        const res = await hotArticleListUsingGet({
        });
        if (res?.data) {
            setHotArticleList(res?.data);
        }
        setLoading(false)
    }
    const fadeAndScaleIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
      `;
    const handleCommentVary = () =>{
        if(data?.isComment==1)
        {
            handleCommentModalOpen(true)
        }else{
            notification.error({
                message: '文章评论已关闭',
                description: '作者关闭了评论区',
            });
        }

    }

    useEffect(() => {
        LoadDta();
        loadHotArticleList();
        getComment(param.id);
    }, []);
    useEffect(() => {
         console.log(data)
        const numberElement = document.getElementById("content");
        if(data && data.content) {
            console.log(data.content)
            numberElement.innerHTML = marked.parse(data.content);
        }
    }, [data]);
  useEffect(() => {
    getComment(param.id)
  }, [commentModalOpen]);
    return(
        <PageContainer>
            <Card
                actions={[
                   <div style={{fontSize: '16px'}} > <LikeOutlined  key="setting" style={{marginRight: '10px',fontSize: '16px'}} onClick={onGood} />{data?.likes}</div>,
                    <div style={{fontSize: '16px'}}> <MessageOutlined onClick={handleCommentVary} style={{marginRight: '10px',fontSize: '16px'}} key="edit" />{commentList?.length}</div>,
                    <EllipsisOutlined key="ellipsis" style={{fontSize: '16px'}} onClick={()=>notification.info({
                        message: '作者寄语',
                        description: '感谢您看完本文章，希望您喜欢。',
                        duration: 3,
                        icon:<SmileTwoTone />,
                    })} />,
                ]}
                style={{
                marginTop: '-0.3%',
                width: '75%',
                height: '40%',
                animation: `${fadeAndScaleIn} 1.5s ease-in-out`
            }}>
                <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                    <p style={{fontWeight: 'bold', fontSize: '30px', marginBottom: "2px"}}>{data?.title}</p>
                </div>

                <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center', marginBottom: "15px"}}>
                    <a style={{fontWeight: 'bold', fontSize: '20px', color: 'gray'}}>{data?.summary}</a>
                </div>

                <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                    <Image src={data?.thumbnail}>

                    </Image>
                </div>
                <div id={'content'} style={{whiteSpace: 'pre-wrap'}}>

                </div>
                <div style={{display: 'flex', justifyContent: 'right', alignItems: 'center',fontSize: '16px',fontWeight: 'bold',color: 'gray'}}>
                    <EditFilled/>
                    <div style={{marginLeft: '6px',}}>发表于：</div>
                    <a style={{
                        color: 'gray',
                        marginRight: '10px'
                    }}>{data?.createTime.split(" ")[0]}</a><VideoCameraFilled/><a
                    style={{marginRight: '6px'}}></a>{data?.viewCount}次观看
                </div>
                <CommentModal key="1" isOpen={commentModalOpen} onClose={ondrawClose} data={commentList}/>
            </Card>


            <Card hoverable={true} onClick={() => {history.push(`/userConfig/${data?.createBy}`)}} title={<div style={{
                fontWeight: 'bold',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
            }}>作者详情</div>} style={{
                width: '20%',
                position: "fixed",
                right: "2%",
                top: "7%",
                height: '36%',
                animation: `${fadeAndScaleIn} 1.5s ease-in-out`,
            }}>
                <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>

                  <Avatar
                        shape="square"
                        size={{xs: 32, sm: 40, md: 48, lg: 96, xl: 120, xxl: 150}}
                        src={"https://openapi--bucket.oss-cn-beijing.aliyuncs.com/OIP-C.jfif"}
                    />
                </div>
                <div  style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                    <p style={{fontWeight: 'bold', fontSize: '20px'}}>{data?.writerName}</p>
                </div>
                <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                    <p style={{fontWeight: 'bold', fontSize: '20px'}}>{data?.writerIntro}</p>
                </div>

            </Card>
            <Card title={<div style={{fontWeight: 'bold'}}> 热门文章</div>} style={{  width: '20%',
                position: "fixed",
                right: "2%",
                top: "44%",
                height: '40%',
                animation: `${fadeAndScaleIn} 1.5s ease-in-out`,overflow:'auto',maxHeight:'30%'}}>
                <List
                    className="Forum-List"
                    loading={loading}
                    itemLayout="vertical"
                    dataSource={hotArticleList}
                    size="small"
                    renderItem={(item, index) => {
                        return(
                            <div style={{marginBottom: '10px'}}><a href={`/forum/${item.id}`} style={{fontWeight: 'bold',fontSize: '17px',color: 'black',marginBottom: '10px'}}>{item.title}<a style={{marginLeft: '10px',color: 'black',fontWeight: 'normal'}}> - {item.viewCount}次观看<br/></a></a></div>
                        );
                    }
                    }
                ></List>
            </Card>
        </PageContainer>
    );
};

export default Index;
